package com.caifu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caifu.mapper.*;
import com.caifu.pojo.*;
import com.caifu.service.IHealthArchiveService;
import com.caifu.service.WardRoundService;
import com.caifu.util.Constance;
import com.caifu.util.Util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 查房记录表 服务实现类
 * </p>
 *
 * @author lyf
 * @since 2020-11-09
 */
@Service
public class WardRoundServiceImpl extends ServiceImpl<YlWardRoundRecordMapper, YlWardRoundRecord> implements WardRoundService {

    @Autowired
    private IHealthArchiveService iHealthArchiveService;

    @Autowired
    private YlHealthyArchivesRecordMapper archivesMapper;

    @Autowired
    private YlHealthyArchivesMapper archivesMapper_two;

    @Autowired
    private YlUserHistoryRecordMapper userHistoryMapper;

    @Autowired
    private YlPhysiqueCheckRecordMapper checkMapper;

    @Autowired
    private YlPhysiqueCheckMapper checkMapper_two;

    @Autowired
    private YlWardRoundRecordMapper roundRecordMapper;

    @Autowired
    private YlCheckInfoMapper checkInfoMapper;

    @Autowired
    private YlLaboratoryInspectMapper laboratoryInspectMapper;

    @Autowired
    private YlPreliminaryDiagnosisMapper preliminaryDiagnosisMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveBasicHealthyInfo(YlWardRoundRecord wardRound,YlHealthyArchivesRecord healthyArchives, YlUserHistoryRecord history, SysUser sysUser) throws Exception {
        JSONObject result = new JSONObject();
        if(null==sysUser){
            result.put("code","1001");
            result.put("codeDesc","管理员登录超时！");
            return result;
        }
        if(null==healthyArchives||null==history){
            result.put("code","1002");
            result.put("codeDesc","要添加的信息为空！");
            return result;
        }
        try {
            healthyArchives.setTellerNo(sysUser.getUserNo()+"");
            healthyArchives.setCreateTime(Constance.currentDateTime());
            history.setTellerNo(sysUser.getUserNo()+"");
            history.setCreateTime(Constance.currentDateTime());
            healthyArchives.setBatchNo(wardRound.getId());
            history.setBatchNo(wardRound.getId());
            //添加
            roundRecordMapper.insert(wardRound);
            archivesMapper.insert(healthyArchives);
            userHistoryMapper.insert(history);
            result.put("code","0000");
            result.put("batchNo",wardRound.getId());
            result.put("codeDesc","保存成功！");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.put("code","9999");
            result.put("codeDesc","添加失败！");
            return result;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject savePhysiqueCheckInfo(YlPhysiqueCheckRecord physiqueCheck, SysUser sysUser) throws Exception {
        JSONObject result = new JSONObject();
        if(null==sysUser){
            result.put("code","1001");
            result.put("codeDesc","管理员登录超时！");
            return result;
        }
        if(null==physiqueCheck){
            result.put("code","1002");
            result.put("codeDesc","要添加的信息为空！");
            return result;
        }
        try {
            physiqueCheck.setCreateTime(Constance.currentDateTime());
            physiqueCheck.setTellerNo(sysUser.getUserNo()+"");
            //查询原体格检查信息是否存在
            checkMapper.deleteById(physiqueCheck.getBatchNo());
            checkMapper.insert(physiqueCheck);
            result.put("code","0000");
            result.put("codeDesc","保存成功！");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.put("code","9999");
            result.put("codeDesc","保存失败！");
            return result;
        }
    }

    @Override
    @Transactional
    public List<YlCheckInfo> getCheckInfoList(String type, String pensionNo) {
        QueryWrapper<YlCheckInfo> qw  = new QueryWrapper<>();
        qw.eq("CHECK_TYPE",type);
        qw.eq("PENSION_NO",pensionNo);
        qw.eq("STATUS","1");
        qw.orderByAsc("CREATE_TIME");
        return checkInfoMapper.selectList(qw);
    }

    @Override
    @Transactional
    public List<YlCheckInfo> getCheckInfoList(String ids) {
        if(StringUtils.isNotBlank(ids)) {
            QueryWrapper<YlCheckInfo> qw = new QueryWrapper<>();
            qw.in("CHECK_NO", ids.split(","));
            qw.orderByAsc("CREATE_TIME");
            return checkInfoMapper.selectList(qw);
        }else{
            return new ArrayList<YlCheckInfo>();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveLaboratoryRecord(String data, String batchNo) {
        try{
            laboratoryInspectMapper.delete(new QueryWrapper<YlLaboratoryInspect>().eq("batch_no",batchNo));
            if(StringUtils.isNotBlank(data)) {
                JSONArray arr = JSONArray.fromObject(data);
                if(arr != null && arr.size() > 0){
                    for(int i = 0;i<arr.size() ;i++){
                        JSONObject obj = arr.getJSONObject(i);
                        YlLaboratoryInspect li = new YlLaboratoryInspect();
                        li.setBatchNo(batchNo);
                        li.setSort(i+1);
                        li.setText(obj.getString("text"));
                        li.setType(obj.getString("type"));
                        laboratoryInspectMapper.insert(li);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    @Transactional
    public List<YlLaboratoryInspect> getLaboratoryRecord(String batchNo) {
        return laboratoryInspectMapper.selectList(new QueryWrapper<YlLaboratoryInspect>().eq("batch_no",batchNo));
    }

    @Override
    @Transactional
    public List<Map<String, String>> getLaboratoryRecord_two(String batchNo) {
        return laboratoryInspectMapper.getLaboratoryRecord(batchNo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePreliminaryInspection(YlPreliminaryDiagnosis pd) {
        preliminaryDiagnosisMapper.delete(new QueryWrapper<YlPreliminaryDiagnosis>().eq("batch_no",pd.getBatchNo()));
        preliminaryDiagnosisMapper.insert(pd);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editPreliminaryInspection(YlPreliminaryDiagnosis pd,String userNo) {
        preliminaryDiagnosisMapper.updateById(pd);
        archivesMapper_two.delete(new QueryWrapper<YlHealthyArchives>().eq("USER_NO",userNo));
        checkMapper_two.delete(new QueryWrapper<YlPhysiqueCheck>().eq("USER_NO",userNo));
        YlHealthyArchivesRecord har = archivesMapper.selectOne(new QueryWrapper<YlHealthyArchivesRecord>().eq("batch_no",pd.getBatchNo()));
        YlPhysiqueCheckRecord pcr = checkMapper.selectOne(new QueryWrapper<YlPhysiqueCheckRecord>().eq("batch_no",pd.getBatchNo()));
        YlHealthyArchives ha = Util.copy(har,YlHealthyArchives.class);
        YlPhysiqueCheck pc = Util.copy(pcr,YlPhysiqueCheck.class);
        archivesMapper_two.insert(ha);
        checkMapper_two.insert(pc);
        YlWardRoundRecord wr = roundRecordMapper.selectById(pd.getBatchNo());
        wr.setStatus("2");
        roundRecordMapper.updateById(wr);
    }

    @Override
    @Transactional
    public YlPreliminaryDiagnosis getPreliminaryDiagnosis(String batchNo) {
        return preliminaryDiagnosisMapper.selectOne(new QueryWrapper<YlPreliminaryDiagnosis>().eq("batch_no",batchNo));
    }

    @Override
    @Transactional
    public Map<String, String> getUserInfo(String userNo) {
        return roundRecordMapper.getUserInfo(userNo);
    }

    @Override
    @Transactional
    public Map<String, String> getInspectInfo(String batchNo) {
        return roundRecordMapper.getInspectInfo(batchNo);
    }

    @Override
    @Transactional
    public List<Map<String, String>> getList(int start, int pageSize, String buildingNo, String startDate, String endDate,String userName) {
        return roundRecordMapper.getList(start,pageSize,buildingNo,startDate,endDate,userName);
    }

    @Override
    @Transactional
    public int getListCount(String buildingNo, String startDate, String endDate,String userName) {
        return roundRecordMapper.getListCount(buildingNo,startDate,endDate,userName);
    }
}
